#!/bin/bash

# MongoDB 安全配置脚本 - Ubuntu 24.04
# 用法: ./setup-mongodb-ubuntu.sh

set -e

echo "🔒 配置 MongoDB 安全设置..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查 MongoDB 是否运行
if ! systemctl is-active --quiet mongod; then
    echo -e "${RED}MongoDB 未运行，请先启动 MongoDB${NC}"
    echo -e "${YELLOW}sudo systemctl start mongod${NC}"
    exit 1
fi

echo -e "${YELLOW}创建 MongoDB 管理员用户...${NC}"

# 创建管理员用户
mongosh admin --eval "
try {
  db.createUser({
    user: 'admin',
    pwd: 'WebNotes@Admin2024!',
    roles: [
      { role: 'userAdminAnyDatabase', db: 'admin' },
      { role: 'readWriteAnyDatabase', db: 'admin' }
    ]
  });
  print('管理员用户创建成功');
} catch (e) {
  if (e.code === 11000) {
    print('管理员用户已存在');
  } else {
    throw e;
  }
}
"

echo -e "${YELLOW}创建应用专用用户...${NC}"

# 创建应用用户
mongosh web-notes-prod --eval "
try {
  db.createUser({
    user: 'webnotesuser',
    pwd: 'WebNotes@App2024!',
    roles: [
      { role: 'readWrite', db: 'web-notes-prod' }
    ]
  });
  print('应用用户创建成功');
} catch (e) {
  if (e.code === 11000) {
    print('应用用户已存在');
  } else {
    throw e;
  }
}
"

echo -e "${YELLOW}配置 MongoDB 认证...${NC}"

# 备份原配置文件
sudo cp /etc/mongod.conf /etc/mongod.conf.backup

# 启用认证
sudo tee /etc/mongod.conf > /dev/null << 'EOF'
# mongod.conf
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

# 启用安全认证
security:
  authorization: enabled
EOF

echo -e "${YELLOW}重启 MongoDB 服务...${NC}"

# 重启 MongoDB
sudo systemctl restart mongod

# 等待服务启动
sleep 5

# 测试连接
if mongosh --quiet --eval "db.runCommand('ismaster')" > /dev/null 2>&1; then
    echo -e "${GREEN}MongoDB 配置完成${NC}"
else
    echo -e "${RED}MongoDB 启动失败，恢复原配置...${NC}"
    sudo cp /etc/mongod.conf.backup /etc/mongod.conf
    sudo systemctl restart mongod
    exit 1
fi

echo -e "\n${GREEN}MongoDB 安全配置完成！${NC}"
echo -e "\n=== 用户信息 ==="
echo -e "管理员用户: ${YELLOW}admin${NC}"
echo -e "管理员密码: ${YELLOW}WebNotes@Admin2024!${NC}"
echo -e "应用用户: ${YELLOW}webnotesuser${NC}"
echo -e "应用密码: ${YELLOW}WebNotes@App2024!${NC}"

echo -e "\n=== .env 配置 ==="
echo -e "请在 ${YELLOW}/var/www/web-notes/web-notes-backend/.env${NC} 中使用以下配置："
echo -e "${YELLOW}MONGODB_URI=mongodb://webnotesuser:WebNotes%40App2024%21@localhost:27017/web-notes-prod${NC}"

echo -e "\n=== 连接测试 ==="
echo -e "测试管理员连接: ${YELLOW}mongosh -u admin -p WebNotes@Admin2024! --authenticationDatabase admin${NC}"
echo -e "测试应用连接: ${YELLOW}mongosh -u webnotesuser -p WebNotes@App2024! --authenticationDatabase web-notes-prod web-notes-prod${NC}"

echo -e "\n${YELLOW}安全建议:${NC}"
echo -e "1. 请修改默认密码"
echo -e "2. 定期备份数据库"
echo -e "3. 监控数据库连接"